<template>
  <div class="mobile-upload">
    <div class="header">
      <h2>图片上传</h2>
      <p class="app-name">{{ appName }}</p>
    </div>
    
    <div class="upload-section">
      <div class="upload-area" @click="triggerFileInput" :class="{ 'uploading': uploading }">
        <div v-if="!selectedFile && !uploading" class="upload-placeholder">
          <el-icon class="upload-icon"><Plus /></el-icon>
          <p>点击选择图片</p>
          <p class="upload-tip">支持 JPG、PNG 格式，大小不超过 10MB</p>
        </div>
        
        <div v-else-if="uploading" class="uploading-state">
          <el-icon class="is-loading upload-icon"><Loading /></el-icon>
          <p>正在上传...</p>
        </div>
        
        <div v-else class="preview-area">
          <img :src="previewUrl" alt="预览图片" class="preview-image" />
          <div class="preview-actions">
            <el-button @click.stop="removeImage" type="danger" size="small">删除</el-button>
            <el-button @click.stop="triggerFileInput" type="primary" size="small">重新选择</el-button>
          </div>
        </div>
      </div>
      
      <input 
        ref="fileInput" 
        type="file" 
        accept="image/*" 
        @change="handleFileSelect" 
        style="display: none"
      />
      
      <div class="upload-actions" v-if="selectedFile && !uploading">
        <el-button @click="uploadImage" type="primary" size="large" :loading="uploading">
          开始识别
        </el-button>
      </div>
    </div>
    
    <!-- 识别结果 -->
    <div class="result-section" v-if="recognitionResult">
      <h3>识别结果</h3>
      <div class="result-card">
        <div class="result-header">
          <!-- <span class="record-id">记录ID: {{ recognitionResult.recordId }}</span> -->
          <el-tag :type="recognitionResult.danger === '1' ? 'danger' : 'success'">
            {{ recognitionResult.danger === '1' ? '预警' : '正常' }}
          </el-tag>
        </div>
        
        <div class="result-content">
          <div class="result-images">
            <div class="image-item">
              <img :src="getImageUrlFromPath(recognitionResult.inputImg)" alt="输入图片" />
              <p>输入图片</p>
            </div>
            <div class="image-item" v-if="recognitionResult.outputImg">
              <img :src="getImageUrlFromPath(recognitionResult.outputImg)" alt="输出图片" />
              <p>输出图片</p>
            </div>
          </div>
          
          <div class="result-details">
            <div class="detail-item">
              <span class="label">识别结果:</span>
              <!-- 只展示解析后的类别名称 -->
              <span class="value">
                <template v-if="parsedResult.length > 0">
                  {{ parsedResult.map(item => item.class || item.name || '').join('，') }}
                </template>
                <template v-else>
                  无
                </template>
              </span>
            </div>
            <div class="detail-item">
              <span class="label">置信度:</span>
              <span class="value">{{ recognitionResult.confidence || '0' }}%</span>
            </div>
            <div class="detail-item">
              <span class="label">处理状态:</span>
              <el-tag :type="getProcessStatusType(recognitionResult.processStatus)">
                {{ getProcessStatusText(recognitionResult.processStatus) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <span class="label">识别时间:</span>
              <span class="value">{{ formatTime(recognitionResult.createTime) }}</span>
            </div>
          </div>
        </div>
        
        <div class="result-actions">
          <el-button @click="resetUpload" type="primary">继续上传</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Loading } from '@element-plus/icons-vue'
import { setToken, getToken } from '@/utils/auth'
import { getImageUrlFromPath } from '@/utils/image'

const route = useRoute()

const appId = ref(route.query.appId)
const appName = ref(route.query.appName || '未知应用')

const fileInput = ref(null)
const selectedFile = ref(null)
const previewUrl = ref('')
const uploading = ref(false)
const recognitionResult = ref(null)

// 新增：解析后的识别结果
const parsedResult = ref([])

// 检查并设置token
const checkAndSetToken = () => {
  const urlToken = route.query.token
  if (urlToken) {
    setToken(urlToken)
    ElMessage.success('已自动登录')
  } else if (!getToken()) {
    ElMessage.error('缺少登录凭证，请重新扫描二维码')
  }
}

onMounted(() => {
  checkAndSetToken()
})

const triggerFileInput = () => {
  if (uploading.value) return
  fileInput.value.click()
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过10MB')
    return
  }
  
  selectedFile.value = file
  
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const removeImage = () => {
  selectedFile.value = null
  previewUrl.value = ''
  fileInput.value.value = ''
}

const uploadImage = async () => {
  if (!selectedFile.value || !appId.value) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  try {
    uploading.value = true
    
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('appId', appId.value)
    
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${baseURL}/customer/manualDetection/upload`, {
      method: 'POST',
      body: formData,
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      recognitionResult.value = result.data
      // 解析 JSON 格式的 recResult
      try {
        parsedResult.value = JSON.parse(recognitionResult.value.recResult || '[]')
      } catch (e) {
        parsedResult.value = []
      }
      ElMessage.success('图片识别完成')
    } else {
      ElMessage.error(result.msg || '识别失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请稍后重试')
  } finally {
    uploading.value = false
  }
}

const resetUpload = () => {
  selectedFile.value = null
  previewUrl.value = ''
  recognitionResult.value = null
  parsedResult.value = []
  fileInput.value.value = ''
}

const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间'
  return new Date(timeStr).toLocaleString('zh-CN')
}

const getProcessStatusType = (status) => {
  switch (status) {
    case '0': return 'info'
    case '1': return 'success'
    case '2': return 'danger'
    default: return 'info'
  }
}

const getProcessStatusText = (status) => {
  switch (status) {
    case '0': return '待处理'
    case '1': return '处理成功'
    case '2': return '处理失败'
    default: return '未知状态'
  }
}
</script>


<style scoped>
.mobile-upload {
  padding: 16px;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  height: 100vh;
  overflow-y: auto;
}

.header {
  text-align: center;
  margin-bottom: 24px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
}

.app-name {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.upload-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.upload-area:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.upload-area.uploading {
  cursor: not-allowed;
  opacity: 0.7;
}

.upload-placeholder {
  color: #666;
}

.upload-icon {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 16px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.uploading-state {
  color: #409EFF;
}

.preview-area {
  position: relative;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.upload-actions .el-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

.result-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
}

.result-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.record-id {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.result-content {
  margin-bottom: 16px;
}

.result-images {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  justify-content: center;
}

.image-item {
  text-align: center;
}

.image-item img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.image-item p {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.result-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 8px;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
  min-width: 80px;
}

.detail-item .value {
  color: #333;
  font-size: 14px;
  text-align: right;
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-wrap;
  max-width: 60%;
  flex: 1;
  margin-left: 12px;
}

.result-actions {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.result-actions .el-button {
  width: 100%;
  height: 44px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .mobile-upload {
    padding: 12px;
  }
  
  .result-images {
    flex-direction: column;
    align-items: center;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .detail-item .value {
    text-align: left;
  }
}
</style>